from flask import Flask
from flask_cors import CORS
from flask import request, jsonify, send_file, send_from_directory,make_response
import os
from datetime import datetime
import json
from studata import all_stu_name
from sqlalchemy.exc import IntegrityError
from api.submit_attendance import submit_attendance_bp
from api.get_attendance import get_attendance_bp
from api.get_attendance_summary import get_attendance_summary_bp
from config import Config
from extensions import db
from models import Attendance
from flask_cors import cross_origin
from flask import render_template



app= Flask(__name__)
cors = CORS(app)  # 允许所有源，仅用于测试
# Flask 配置示例
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@192.168.10.128:3306/classmanagement'
# app.config.from_object(Config)
# 关键步骤：绑定 db 和 app
db.init_app(app)
# 关键CORS配置
CORS(app)



@app.route('/')
def home():
    return render_template('login.html')

@app.route('/index_admin')
def index_admin():
    return render_template('index_admin.html')  # 渲染 templates/index.html

@app.route('/index_student')
def index_student():
    return render_template('index_student.html')  # 渲染 templates/index.html

# 为每个iframe内容添加路由
@app.route('/notice/notice.html')
def notice():
    return send_from_directory('static/notice', 'notice.html')

@app.route('/ClassManage/CLSManage.html')
def class_manage():
    return send_from_directory('static/ClassManage', 'CLSManage.html')

@app.route('/attendance/class.html')
def class_attendance():
    return send_from_directory('static/attendance', 'class.html')

@app.route('/attendance/student.html')
def student_attendance():
    return send_from_directory('static/attendance', 'student.html')

@app.route('/Suggestion/suggestion.html')
def suggestion():
    return send_from_directory('static/Suggestion', 'suggestion.html')



# 注册蓝图
app.register_blueprint(submit_attendance_bp, url_prefix='/api')
app.register_blueprint(get_attendance_bp, url_prefix='/api')
app.register_blueprint(get_attendance_summary_bp, url_prefix='/api')


# ----------------- 上传文件 -----------------

# 设置文件保存的文件夹
UPLOAD_FOLDER = 'homework'
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

# 允许上传的文件类型
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'jpg', 'jpeg', 'png', 'gif'}

def allowed_file(filename):
    """检查文件扩展名是否合法"""
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@app.route('/upload', methods=['POST'])
def upload_file():
    # 检查是否有文件上传
    if 'file' not in request.files:
        return jsonify({'error': '未上传文件'}), 400

    file = request.files['file']
    name = request.form.get('name')  # 获取姓名
    clazz=request.form.get('class')  # 获取班级

    # 检查文件是否为空
    if file.filename == '':
        return jsonify({'error': '未选择文件'}), 400

    # 检查文件扩展名是否合法
    if not allowed_file(file.filename):
        return jsonify({'error': '文件类型不允许'}), 400

    # 保存文件到本地
    try:
        # 获取当前日期并格式化为YYYY-MM-DD格式
        current_date = datetime.now().strftime("%Y-%m-%d")
        FOLDER= UPLOAD_FOLDER+"/"+current_date
        if not os.path.exists(FOLDER):
            os.makedirs(FOLDER)
        filename =clazz+"-"+file.filename
        file_path = os.path.join(FOLDER, filename)
        file.save(file_path)
        return jsonify({
            'message': '文件上传成功',
            'name': name,
            'filename': filename
        }), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500


# 设置照片文件夹路径
PHOTO_FOLDER = os.path.join(os.path.dirname(__file__), '2306photo')

@app.route('/get-photo', methods=['POST'])
def get_photo():
    data = request.json
    username = data.get('username')

    if not username:
        return jsonify({'error': 'Username is required'}), 400

     # 检查照片文件是否存在
    photo_path = os.path.join(PHOTO_FOLDER, f'{username}.JPG')
    if os.path.exists(photo_path):
        # 返回照片文件的 URL
        photo_url = f'http://192.168.43.147:4000/photo/{username}.jpg'
        return jsonify({'photoUrl': photo_url})
    else:
        return jsonify({'error': 'Photo not found'}), 404

# 提供照片文件的静态访问
@app.route('/photo/<filename>')
def serve_photo(filename):
    return send_from_directory(PHOTO_FOLDER, filename)


# 关键点：CORS 处理（放在所有路由定义之后，但要在 if __name__ == '__main__' 之前）
@app.after_request
def add_cors_headers(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
    return response


if __name__=='__main__':
    app. run(debug=True,port=5000,host="0.0.0.0")
    